class Snake {
	constructor(options = {}) {
		this.opt = options;
		this.size = this.opt.size || 10;
		this.color = this.opt.color || '#ffc228';
		this.panel = this.opt.panel || {};
		this.init();
	}
	init(){
		this.direction = this.direction || 'right';
		this.snakeArr = [];
		this.body = [{
				x: 2,
				y: 0,
				color: this.color
			}, // 蛇头
			{
				x: 1,
				y: 0,
				color: this.color
			}, //蛇节
			{
				x: 0,
				y: 0,
				color: this.color
			}
		]
	}
	render() {
		// 先移除蛇
		this.remove();
		// 再渲染蛇
		for (let i = 0, len = this.body.length; i < len; i++) {
			let el = this.body[i];
			let div = document.createElement('div');
			div.style.position = 'absolute';
			div.style.width = this.size + "px";
			div.style.height = this.size + "px";
			div.style.left = el.x * this.size + "px";
			div.style.top = el.y * this.size + "px";
			div.style.border = '1px solid #012842';
			div.style.boxSizing = 'border-box';
			div.style.backgroundColor = this.color;
			// dom 缓存到数组
			this.snakeArr.push(div)
			this.panel.appendChild(div)
		}
	}
	remove() {
		if (!this.snakeArr) return
		for (var i = this.snakeArr.length - 1; i >= 0; i--) {
			this.snakeArr[i].remove()
			this.snakeArr.splice(i,1)
		}
	}
	move() {
		let len = this.body.length
		let body = this.body;
		let head = this.body[0];
		let end = this.body[len-1];
		for (let i = len - 1; i > 0; i--) {
			body[i].x = body[i - 1].x;
			body[i].y = body[i - 1].y;
		}
		switch (this.direction) {
			case 'right':
				head.x += 1;
				break;
			case 'bottom':
				head.y += 1;
				break;
			case 'left':
				head.x -= 1;
				break;
			case 'top':
				head.y -= 1;
				break;
			default:
				break;
		}
		
		
	}
	// 新增一节
	add(){
		let len = this.body.length
		let end = this.body[len-1];
		this.body.push({
			x:end.x,
			y:end.y,
			color:end.color
		})
	}
	// 获取蛇头的属性
	getPoint(){
		return {
			x:this.body[0].x,
			y:this.body[0].y
		}
	}
}
